package net.qiqb.subclass;

import cn.hutool.core.util.ReflectUtil;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
import java.util.Optional;

@RedefineClassAgent
public class SubOrder extends OrderDto {

    private String status;

    private String no;

    public SubOrder(String id) {
        super(id);
    }

    public void createInit() {
        this.status = "padding";
    }

    public static SubOrder replace(OrderDto original) throws Exception {
        final SubOrder subOrder = new SubOrder(original.getId());

        Field[] parentFields = original.getClass().getDeclaredFields();
        Field[] subFields = ReflectUtil.getFields(subOrder.getClass());

        // 复制父类对象中的值到子类对象
        for (Field parentField : parentFields) {
            if (Modifier.isFinal(parentField.getModifiers())) {
                continue;
            }
            final Optional<Field> any = Arrays.stream(subFields).filter(subField -> subField.getName().equals(parentField.getName())).findAny();
            if (any.isPresent()){
                Field subField = any.get();
                parentField.setAccessible(true);
                subField.setAccessible(true);
                subField.set(subOrder, parentField.get(original));
            }
        }
        subOrder.createInit();
        return subOrder;
    }


}
